package code.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import code.db.DBExecutor;
import code.db.DBExecutorFactory;
import code.domain.Table;
/**
 * 数据库应用工具类
 * @author puxin.zhang
 *
 */
public class DBUtils {
	
	private static Log log = LogFactory.getLog(DBUtils.class);
	
	private static DataSource datasource;
	private static Connection dbConnection;
	/**
	 * 获取数据源对象
	 * @return
	 */
	public static DataSource getDatasource(){
		if(datasource == null){
			datasource = (DataSource) CodeGeneratorContext.getBean("dataSource");
		}
		return datasource;
	}
	/**
	 * 获取数据库连接对象 Connection
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException{
		if(dbConnection == null){
			dbConnection = getDatasource().getConnection();
		}
		return dbConnection;
	}
	/**
	 * 获取指定的表信息(包括表的列信息)
	 * @param tableNames
	 * @return
	 */
	public static Table getTable(String tableName){
		DBExecutorFactory executorFactory = (DBExecutorFactory) CodeGeneratorContext.getBean("dbExecutorFactory");
		DBExecutor executor = executorFactory.getExecutor();
		Table table = executor.getTable(tableName);
		return table;
	}
}
